package com.zx.map.controller;

import com.zx.map.common.ManageCommonHelper;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.OrdLogService;
import com.zx.map.service.domain.OrdLogDomain;
import com.zx.map.service.domain.ReportOrdLogDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.OrdLogModel;
import com.zx.map.utils.SUConstants;
import com.zx.platform.context.DirectoryInfoContext;
import com.zx.platform.service.domain.ManageSessionDomain;
import com.zx.platform.service.model.OperatorInfoModel;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.report.ReportUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/manage/ordLogOffline")
public class OrdLogOfflineController {
    /**
     * log
     */
    private static Logger log = Logger.getLogger(OrdLogOfflineController.class);

    @Autowired
    private OrdLogService ordLogService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private MerchantInfoService merchantInfoService;

    /**
     * 交易查询     *
     *
     * @param domain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/historyOrderList")
    public String historyOrderList(OrdLogDomain domain, Model model,
                                   HttpServletRequest request) {

        try {// 初始化信息
            Integer pageNum = domain.getPageNum();
            Integer pageSize = domain.getPageSize();
            Integer pageCount = domain.getPageCount();
            if (null == pageNum) {
                pageNum = 1;
            }
            if (null == pageSize) {
                pageSize = SUConstants.PAGE_COUNT;
            }
            domain.setPageNum(pageNum);
            domain.setPageSize(pageSize);
            if (StringUtils.isBlank(domain.getBeginDate())) {
                domain.setBeginDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd"));
            }
            if (StringUtils.isBlank(domain.getEndDate())) {
                domain.setEndDate(PmpUtils.dateToString(new Date(),
                        "yyyy-MM-dd"));
            }
            //查找当前操作员对应的代理商
            ManageSessionDomain userinfo = (ManageSessionDomain) request.getSession().getAttribute("_LOGONUSER_");
            OperatorInfoModel curOperatorInfo = userinfo.getOperatorInfoModel();
            domain.setMerSysAccount(curOperatorInfo.getLoginName());//仅查询当前用户自身的数据
            Map map = ordLogService.getPageByDomain(null, domain);
            List<OrdLogModel> menuModelList = (List<OrdLogModel>) map.get("list");
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", menuModelList);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            model.addAttribute("model", domain);
            return "/jsp/map/ordlogoffline/historyOrderList";
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * 历史交易下载
     *
     * @param domain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/downloadHistoryOrderList")
    public String downloadHistoryOrderList(OrdLogDomain domain, Model model,
                                           HttpServletRequest request, HttpServletResponse response) {

        try {
            //查找当前操作员，看期是否有对应的代理商
            ManageSessionDomain userinfo = (ManageSessionDomain) request.getSession().getAttribute("_LOGONUSER_");
            OperatorInfoModel curOperatorInfo = userinfo.getOperatorInfoModel();
            domain.setMerSysAccount(curOperatorInfo.getLoginName());//仅查询当前用户自身的数据
            if (StringUtils.isBlank(domain.getBeginDate())) {
                domain.setBeginDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd"));
            }
            if (StringUtils.isBlank(domain.getEndDate())) {
                domain.setEndDate(PmpUtils.dateToString(new Date(),
                        "yyyy-MM-dd"));
            }
            List<OrdLogModel> ordLogList = ordLogService.getListByOrdLogDomain(null, domain);
            List<ReportOrdLogDomain> reportList = new ArrayList();
            for (OrdLogModel o : ordLogList) {
                //交易状态  增加为空检查
                if (StringUtils.isNotBlank(o.getTransStatus())) {
                    o.setTransStatus(DirectoryInfoContext.getCaptionByKeyAndValue("2130", o.getTransStatus()));
                }
                ReportOrdLogDomain temp = new ReportOrdLogDomain();
                BeanUtils.copyProperties(o, temp);
                //设置订单类型  商户名称 代理商名称
                MerchantInfoModel tempMer = merchantInfoService.getModelByKey(o.getMerchantId());
                AgentInfoModel tempAgent = agentInfoService.getAgentInfoModelBySysAccount(o.getAgentSysAccount());
                temp.setAgentName(tempAgent.getAgentName());
                temp.setMerName(tempMer.getMerchantName());
                if (ManageCommonHelper.TRANSTYPE_INCOME.equals(o.getTransType())) {
                    temp.setTransType("扫码收款");
                } else if (ManageCommonHelper.TRANSTYPE_INCOME.equals(o.getTransType())) {
                    temp.setTransType("无卡收款");
                } else if (ManageCommonHelper.TRANSTYPE_INCOME.equals(o.getTransType())) {
                    temp.setTransType("刷卡收款");
                } else if (ManageCommonHelper.TRANSTYPE_OFFLINE_INCOME.equals(o.getTransType())) {
                    temp.setTransType("线下扫码");
                }
                reportList.add(temp);
            }

            Map<Integer, Object> formatAttr = new HashMap<Integer, Object>();
            formatAttr.put(1, ReportUtil.Date_cro);
            try {

                String[] header = null;
                header = new String[]{"创建时间", "交易流水号", "订单类型", "订单金额", "商户账号", "商户名称",
                        "代理商账号", "代理商名称", "收款订单号", "交易状态", "备注"};
                String sts = ReportUtil.exportReport(header, reportList, null,
                        "历史交易查询", formatAttr, null, response);
                String[] st = sts.split("#");
                ReportUtil.download(response, st[0], st[1]);
            } catch (Exception e) {
                log.error("交易流水", e);
            }
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
        return null;
    }
}
